package com.report.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.report.dto.request.WebMemberReq;
import com.report.dto.request.WechatPhoneReq;
import com.report.dto.request.WechatReq;
import com.report.dto.response.MemberRes;
import com.report.entity.Member;
import com.report.properties.WxProperties;
import com.report.service.IMemberService;
import com.report.wx.WechatService;
import com.zmh.framework.annotation.LogAnnotation;
import com.zmh.framework.exception.ResultException;
import com.zmh.framework.util.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URLEncoder;

/**
 * @author summer
 * @date 2024-06-18 9:28
 */
@Controller
@RequestMapping(value = "/wechat")
@Slf4j
@AllArgsConstructor
public class WechatController {

      private final WechatService wechatService;

      private final WxMpService wxMpService;

      private final WxProperties wxProperties;


    @GetMapping("/authorize")
    public String authorize() throws UnsupportedEncodingException {
        String result=wxMpService.getOAuth2Service().buildAuthorizationUrl(wxProperties.getRedirectUrl(), WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode("http://a5382095.imwork.net/", CharsetUtil.UTF_8));
        log.info("微信网页授权，获取code，result={}",result);
        return "redirect:"+result;
    }


    @GetMapping("/userInfo")
    public void userInfo(@RequestParam("code") String code) {
         try {
            WxOAuth2AccessToken  wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);

            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
            log.info("userInfo={}", JSON.toJSONString(userInfo));
            } catch (WxErrorException e) {
                throw new ResultException(e.getMessage());
            }
    }



      @GetMapping(value = "/login/{type}")
      @ResponseBody
      public Result<WxMpQrCodeTicket> login(@PathVariable Integer type){

          return Result.successResult(wechatService.login(type));
      }



    /**
     * 验证公众号配置
      * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/checkSign")
    @ResponseBody
    public String configAccess(String signature, String timestamp, String nonce, String echostr) {
         return wechatService.configAccess(signature, timestamp, nonce, echostr);
    }


    /**
     * 关注微信公众号的操作事件
     * @param xml
     * @return
     */
    @PostMapping(value = "/checkSign")
    @ResponseBody
    public String receiver(@RequestBody String xml){
       return wechatService.receiver(xml);
    }


    /**
     * 小程序获取手机号码
     * @param wechatPhoneReq
     * @return
     */
    @PostMapping(value = "/getUserPhone")
    @ResponseBody
    @LogAnnotation(msg = "小程序")
    public Result<MemberRes> userPhone(@RequestBody WechatPhoneReq wechatPhoneReq)  {
         return Result.successResult(wechatService.getUserPhone(wechatPhoneReq));
    }

    private final IMemberService memberService;

    @PostMapping(value = "/updateAvatarUrl")
    @ResponseBody
    public Result<MemberRes> updateAvatarUrl(@RequestBody WebMemberReq webMemberRes){
       memberService.updateAvatarUrl(webMemberRes);
        Member byId = memberService.getById(webMemberRes.getUserId());
        return Result.successResult(Convert.convert(MemberRes.class, byId));
    }


    /**
     * 获取微信的openId
     * @param cod
     * @return
     * @throws WxErrorException
     */
    @PostMapping(value = "/getOpenId")
    @ResponseBody
    public Result<String> openId(@RequestBody WechatReq wechatReq)  {
        return Result.successResult(wechatService.getOpenId(wechatReq));
    }


}
